package com.zhongfl.crm.lixiao.message;

import com.zhongfl.crm.enums.boss.WorkOrderTypeCode;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.batch.service.LxDeliverOrderCreateService;
import com.zhongfl.crm.lixiao.config.MailConfigInfo;
import com.zhongfl.crm.mail.MailService;
import com.zhongfl.crm.mail.bean.MailMessage;
import com.zhongfl.crm.mail.bean.MailMessageBuilder;
import com.zhongfl.crm.mail.enums.MailTypeEnum;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.OrderCreatedMessage;
import com.zhongfl.crm.model.boss.ServiceResult;
import com.zhongfl.crm.model.boss.TopicConsts;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.WorkOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.KafkaException;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import tech.heptagram.core.common.util.JsonUtil;

import javax.annotation.Resource;
import java.util.Objects;


/**
 * 订单创建自动创建采集工单消费者
 *
 * @author wang.yuchuan
 * @date 2018/7/30
 */
@Component
@Slf4j
public class OrderCreatedInformationConsumer extends AbstractKafkaConsumer {

    @Resource
    private MailService mailService;

    @Resource
    private MailConfigInfo mailConfigInfo;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private LxUserService lxUserService;

    @Resource
    private LxDeliverOrderCreateService lxDeliverOrderCreateService;


    /**
     * 励销同步订单到boss创建采集工单消息
     *
     * @param consumerRecord
     * @throws KafkaException
     */
    @KafkaListener(topics = {TopicConsts.CREATED_ORDER_INFORMATION_NOTIFY_TOPIC})
    public void listen(ConsumerRecord<String, String> consumerRecord) throws KafkaException {
        super.handler(consumerRecord, TopicConsts.CREATED_ORDER_INFORMATION_NOTIFY_TOPIC);
    }

    @Override
    public void execute(ConsumerRecord<String, String> consumerRecord) throws KafkaException {
        log.info("consumer msg: {} {} {}", consumerRecord.key(), consumerRecord.topic(), consumerRecord.value());

        try {
            //取交付部门的信息
            OrderCreatedMessage message = JsonUtil.fromJson(consumerRecord.value(), OrderCreatedMessage.class);
            log.info("创建订单采集工单开始{}",message.getOrderNo());

            String orderNo = message.getOrderNo();
            //取励销商务的信息
            LxUser lxUser = lxUserService.findByLxId(message.getLxUserId());
            if(Objects.isNull(lxUser)){
                throw new CRMException("自动创建采集工单过程中，没有在本地找到励销商务的信息");
            }
            String operStaffCode = lxUser.getStaffCode();
            String operStaffName = lxUser.getStaffName();
            Integer amibaId = Integer.valueOf(message.getDeliveryAmibaId());

            ServiceResult<String> stringServiceResult = workOrderService.create(orderNo,
                    operStaffCode, WorkOrderTypeCode.INFORMATION, "系统自动创建，无备注",
                    operStaffName, amibaId);
            log.info("采集工单创建结果{}",stringServiceResult.toString());

            // 创建资料采集工单的时候，会修改交付订单状态，触发修改客户订单状态，然后客户订单会新增客户订单信息变更任务，在boss->crm更新的时候重新更新客户订单状态。
            // 这里不会影响正常使用，但是任务会执行多次

            lxDeliverOrderCreateService.createLiXiaoDeliverOrder(message);


        } catch (Exception e) {
            log.error(e.getMessage());
            this.sendErrorMessage(e);
        }

    }

    private void sendErrorMessage(Exception e) {
        MailMessage mailMessage = MailMessageBuilder.builder()
                .mailTypeEnum(MailTypeEnum.NOTIFY_ERROR)
                .subject("创建采集工单异常-" + mailConfigInfo.getActiveProfiles())
                .to(mailConfigInfo.getDefaultTo())
                .addData("title", "创建采集工单异常,类名：OrderCreatedInformationConsumer")
                .addData("message", e.getMessage())
                .build();

        mailService.send(mailMessage);
    }

}
